/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vita.vitasolution.db.beans;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import vita.vitasolution.db.dictionaries.CaseState;
import vita.vitasolution.db.entities.Case;
import vita.vitasolution.db.entities.User;

/**
 *
 * @author harker777
 */
@Named
public class CaseDAO extends AbstractDAO<Case> {

	@PersistenceContext(unitName = "VitaSolutionPU")
	private EntityManager em;

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

	public CaseDAO() {
		super(Case.class);
	}

	@Override
	public void create(Case entity) {
		entity.setCaseState(CaseState.OPENED);
		getEntityManager().persist(entity);
		getEntityManager().flush();
	}

	public List<Case> findOrderedInterval(int from, int length, String orderBy) {
		CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
		CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();

		Root<Case> root = criteriaQuery.from(Case.class);
		criteriaQuery.select(root);

		if ("fund".equals(orderBy)) {
			criteriaQuery.orderBy(criteriaBuilder.desc(root.get("fund")));
		} else if ("date".equals(orderBy)) {
			criteriaQuery.orderBy(criteriaBuilder.desc(root.get("postDate")));
		}

		Query query = em.createQuery(criteriaQuery);
		query.setFirstResult(from);
		query.setMaxResults(length);

		return query.getResultList();
	}

	public List<Case> findCasesOfUserInState(User user, CaseState caseState) {
		CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
		CriteriaQuery cq = cb.createQuery();

		Predicate criteria = cb.conjunction();

		Root<Case> root = cq.from(Case.class);
		criteria = cb.and(criteria, cb.equal(root.get("user"), user));
		criteria = cb.and(criteria, cb.equal(root.get("caseState"), caseState));

		cq.where(criteria);
		return em.createQuery(cq).getResultList();
	}
}
